<?php
namespace Mobile\Controller;

class BindController extends BaseController {

    public function __construct() {
        parent::__construct();
    }
	
	public function autobind(){
		
		$is_first = $this->memberinfo['is_first'];
		$where = array(
			"uid" => $this->memberinfo['uid']
		);
		if($is_first == 1){
			//自动绑定
			$res = $this->_bind();
			//设置$is_first 为0
			if($res){
				$this->memberModel->where($where)->setField("is_first",0);
				return true;
			}
		}
		return false;
		
	}
	
	
	protected function _bind(){
		
	   if(!$this->openid){
		   return false;
	   }
	   $data = $this->wxuserinfo;
	   
	   $r = $this->memberModel->where(array("openid"=>$this->openid))->find();
	   if($r){
		   if($r['uid'] == $this->uid){
			   $res = $this->memberModel->where(array("uid"=>$this->uid))->save($data);
			   return true;
		   }else{
			   //先解绑别人
				return false;
		   }
	   }
	   
	   $res = $this->memberModel->where(array("uid"=>$this->uid))->save($data);
	   
	   if($res){
		   return true;
	   }
	}
	

	//绑定微信
    public function wechat(){
		
	   if(!$this->openid){
		   return_json(1,"绑定失败");
	   }
	   $data = $this->wxuserinfo;
	   
	   $r = $this->memberModel->where(array("openid"=>$this->openid))->find();
	   if($r){
		   if($r['uid'] == $this->uid){
			   $res = $this->memberModel->where(array("uid"=>$this->uid))->save($data);
			   return_json(0,"绑定成功",'','/mobile/user');
		   }else{
			   //先解绑别人
				$data2 = array(
					"openid" => NULL,
					"unionid" => NULL,
					"subscribe" => NULL,
					"nickname" => NULL,
					"subscribe_time" => NULL,
					"headimgurl" => NULL,
				);
			   $r2 = $this->memberModel->where(array("uid"=>$r['uid']))->save($data2);
		   }
	   }
	   
	   $res = $this->memberModel->where(array("uid"=>$this->uid))->save($data);
	   
	   if($res){
		   $this->updateMemberSession($this->uid);
		   return_json(0,"绑定成功",'','/mobile/user');
	   }else{
               return_json(1,"已绑定");
           }
	   
	   

    }
	
	//解绑微信
    public function unwechat(){

		$data = array(
			"openid" => NULL,
			"unionid" => NULL,
			"subscribe" => NULL,
			"nickname" => NULL,
			"subscribe_time" => NULL,
			"headimgurl" => NULL,
		);
	   $res = $this->memberModel->where(array("uid"=>$this->uid))->save($data);
	   
	   if($res){
		   $this->updateMemberSession($this->uid);
		   return_json(0,"解绑成功",'','/mobile/user');
	   }
	   
	   return_json(1,"解绑失败");
	
    }

	
 
}